var services = require('./services'),
    ResponseModel = function(){
        this.code = '200';
        this.data = null;
    };

module.exports = function(sid, req, res ,cb){

    try{
		var serv = services[sid];
        if(!serv){ // 当service不存在时
			var error404 = new Error();
            error404.code = 404;
            error404.message = 'Not Found Service : ' + sid;
            throw error404;
        }else{
			var method = serv[req.method.toLowerCase()] || serv[req.method] ;
            if(method){
                // 调用服务
                method(/*params,*/req ,res,function(err ,data){
                    if(err){
                        failureHandler(err ,cb)
                    }else{
                        successHandler(data ,cb);
                    }
                });
            }else{
                var error404 = new Error();
                error404.code = 500;
                error404.message = ' 请求被拒绝! ';
                throw error404;
            }
        }
    }catch(err){
        failureHandler(err ,cb);
    }
}

function successHandler(data ,cb){
	var responseModel = new ResponseModel();
	responseModel.data = data;
	//console.log(data);
	cb.call(this, responseModel);
}

function failureHandler(err ,cb){
	var responseModel = new ResponseModel();
	bn.logger.error(err.stack);
	responseModel.code = '500';
	if(err.code == 404){
		responseModel.code = '404';
	}
	responseModel.data = err.message;
	//if(err instanceof SyntaxError){
	//	responseModel.data = 'invalid parameter!';
	//}
	cb.call(this, responseModel);
}